<script setup lang="ts">
import { delArticleAPI } from "@/apis/publish";
import { ArticlesAPI, ChannelsAPI } from "@/apis/user";
import type {
   ArticleItem,
   ChannelItem,
   channelsDete,
} from "@/types/article";
import { ArrowRight } from "@element-plus/icons-vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import { en, zhCn } from "element-plus/es/locales.mjs";
import { computed, onMounted, ref, watch } from "vue";

// 频道列表
const channels = ref<ChannelItem[]>([]);
// 日期数组
const date = ref<string[]>([]);

// 监听日期
watch(
  date,
  (val) => {
    if (val) {
      ArticleRes.value.begin_pubdate = val[0];
      ArticleRes.value.end_pubdate = val[1];
    } else {
      ArticleRes.value.begin_pubdate = "";
      ArticleRes.value.end_pubdate = "";
    }
  },
  { deep: true }
);

// 获取文章列表query
const ArticleRes = ref<channelsDete>({
  status: "",
  channel_id: "",
  begin_pubdate: "",
  end_pubdate: "",
  page: 1,
  per_page: 10,
});

const articleList = ref<ArticleItem[]>([]);
const total = ref(0);

const getList = async () => {
  const res = await ArticlesAPI(ArticleRes.value);
  // console.log('文章列表',res.data.total_count)
  articleList.value = res.data.results;
  total.value = res.data.total_count;
};
onMounted(() => {
  getList();
});

// 校验规则
const feeFormRules = ref<FormRules<channelsDete>>({
  channel_id: [
    {
      required: true,
      message: "请选择频道",
      trigger: "blur",
    },
  ],
  end_pubdate: [
    {
      required: true,
      message: "请选择有效日期",
      trigger: "blur",
    },
  ],

});

// 整体校验
const ArticleRef = ref<FormInstance>();
// 筛选
const onSubmit = () => {
  // 校验表单
  try {
    ArticleRef.value?.validate(async (res) => {
      if (res) {
        try {
          const res = await ArticlesAPI(ArticleRes.value);
          console.log(res);
          articleList.value = res.data.results;
          total.value = res.data.total_count;
        } catch {}
      }
    });
  } catch {}
};

// 全局配置组件
const language = ref("zh-cn");
const locale = computed(() => (language.value === "zh-cn" ? zhCn : en));
onMounted(async () => {
  const res = await ChannelsAPI();
  // console.log(res)
  channels.value = res.data.channels;
});

// 删除文章
const deleteArticle = (id: string) => {
  ElMessageBox.confirm("确定删除文章吗?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await delArticleAPI(id);
      ElMessage.success("删除成功");
      getList();
    })
    .catch(async () => {});
};
</script>
<template>
  <div class="article">
    <!-- el-card卡片组件带阴影 -->
    <el-card shadow="always">
      <template v-slot:header>
        <div>
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>内容</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </template>
      <!-- 主体表单 -->
      <el-form
        label-width="80px"
        :model="ArticleRes"
        :rules="feeFormRules"
        :ref="'ArticleRef'"
      >
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ArticleRes.status">
            <!-- 文章状态，0-草稿，1-待审核，2-审核通过，3-审核失败，不传为全部 -->
            <el-radio :label="''">全部</el-radio>
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">待审核</el-radio>
            <el-radio :label="2">审核通过 </el-radio>
            <el-radio :label="3">审核失败 </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="频道" prop="channel_id">
          <el-select style="width: 240px" v-model="ArticleRes.channel_id">
            <el-option
              v-for="item in channels"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" style="width: 400px" prop="end_pubdate">
          <el-date-picker
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            range-separator="至"
            value-format="YYYY-MM-DD"
            v-model="date"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">筛选</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 筛选结果 -->
    <el-card shadow="always" style="margin-top: 20px">
      <template v-slot:header>
        <div>
          <p>根据筛选条件共查询到{{ total }}条结果</p>
        </div>
      </template>
      <!-- 表格 -->
      <el-table :data="articleList">
        <el-table-column label="封面" prop="cover">
          <template v-slot="score">
            <el-image
              :src="score.row.cover.images[0]"
              :preview-src-list="score.row.cover.images"
              style="width: 100px; height: 100px"
              fit="cover"
            >
              <template v-slot:error>
                <div class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          label="标题"
          prop="title"
          width="200"
        ></el-table-column>
        <el-table-column label="状态" prop="status">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status === 0" type="info">草稿</el-tag>

            <el-tag v-if="scope.row.status === 1">待审核</el-tag>

            <el-tag v-if="scope.row.status === 2" type="success"
              >审核通过</el-tag
            >
            <el-tag v-if="scope.row.status === 3" type="danger"
              >审核失败</el-tag
            >
            <el-tag v-if="scope.row.status === 4" type="warning">已删除</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="发布时间"
          prop="pubdate"
          width="200"
        ></el-table-column>
        <el-table-column label="阅读数" prop="read_count"></el-table-column>
        <el-table-column label="评论数" prop="comment_count"></el-table-column>
        <el-table-column label="点赞数" prop="like_count"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- circle圆形按钮  plain朴素按钮 -->
            <el-button
              type="primary"
              circle
              plain
              icon="EditPen"
              @click="$router.push(`/publish/${scope.row.id}`)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="Delete"
              circle
              plain
              @click="deleteArticle(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-config-provider :locale="locale">
        <el-pagination
          :page-sizes="[2, 5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:page-size="ArticleRes.per_page"
          v-model:current-page="ArticleRes.page"
          @current-change="getList()"
          @size-change="getList()"
        />
      </el-config-provider>
    </el-card>
    {{ ArticleRes }}
  </div>
</template>

<style scoped>
/* 样式 */
::v-deep(.image-slot) {
  width: 100%;
  height: 100%;
  background-color: #f4f4f4;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
}
</style>
